<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wangxl12.github.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":true},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":true,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":false,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="outline 函数与函数式编程：  一等函数 把函数视为对象 高阶函数 列表推导 vs (map&#x2F;reduce) 函数的参数与返回值  方法和装饰器：  有用的装饰器 由简单到复杂实现各类装饰器">
<meta property="og:type" content="article">
<meta property="og:title" content="python高级编程-part1">
<meta property="og:url" content="https://wangxl12.github.io/2021/10/23/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/python%E9%AB%98%E7%BA%A7%E7%BC%96%E7%A8%8B-part1/index.html">
<meta property="og:site_name" content="WXL&#39;s blog">
<meta property="og:description" content="outline 函数与函数式编程：  一等函数 把函数视为对象 高阶函数 列表推导 vs (map&#x2F;reduce) 函数的参数与返回值  方法和装饰器：  有用的装饰器 由简单到复杂实现各类装饰器">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-10-23T03:16:32.000Z">
<meta property="article:modified_time" content="2021-10-23T11:22:37.210Z">
<meta property="article:author" content="WXL">
<meta property="article:tag" content="python高级编程">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://wangxl12.github.io/2021/10/23/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/python%E9%AB%98%E7%BA%A7%E7%BC%96%E7%A8%8B-part1/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>python高级编程-part1 | WXL's blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="WXL's blog" type="application/atom+xml">
<link href="https://cdn.bootcss.com/KaTeX/0.11.1/katex.min.css" rel="stylesheet" /></head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">WXL's blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Talk is cheap, show me your work.</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">33</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">49</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

  <a href="https://github.com/wangxl12" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangxl12.github.io/2021/10/23/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/python%E9%AB%98%E7%BA%A7%E7%BC%96%E7%A8%8B-part1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/td.jpg">
      <meta itemprop="name" content="WXL">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="WXL's blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          python高级编程-part1
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-10-23 11:16:32 / 修改时间：19:22:37" itemprop="dateCreated datePublished" datetime="2021-10-23T11:16:32+08:00">2021-10-23</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/python%E9%AB%98%E7%BA%A7%E7%BC%96%E7%A8%8B/" itemprop="url" rel="index"><span itemprop="name">python高级编程</span></a>
                </span>
            </span>

          
            <span id="/2021/10/23/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/python%E9%AB%98%E7%BA%A7%E7%BC%96%E7%A8%8B-part1/" class="post-meta-item leancloud_visitors" data-flag-title="python高级编程-part1" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2021/10/23/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/python%E9%AB%98%E7%BA%A7%E7%BC%96%E7%A8%8B-part1/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2021/10/23/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/python%E9%AB%98%E7%BA%A7%E7%BC%96%E7%A8%8B-part1/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1>outline</h1>
<p><strong>函数与函数式编程：</strong></p>
<ul>
<li>一等函数</li>
<li>把函数视为对象</li>
<li>高阶函数</li>
<li>列表推导 vs (map/reduce)</li>
<li>函数的参数与返回值</li>
</ul>
<p><strong>方法和装饰器：</strong></p>
<ul>
<li>有用的装饰器</li>
<li>由简单到复杂实现各类装饰器</li>
</ul>
<span id="more"></span>
<h1>一等函数</h1>
<p><strong>特点：</strong></p>
<ol>
<li>可以运行的时候创建；</li>
<li>可以作为变量，传给函数；</li>
<li>可以作为函数的返回结果。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">factorial</span>(<span class="params">n</span>):</span></span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    return n!</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">1</span> <span class="keyword">if</span> n &lt; <span class="number">2</span> <span class="keyword">else</span> factorial(n - <span class="number">1</span>) * n</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(factorial(<span class="number">5</span>))</span><br></pre></td></tr></table></figure>
<p>既然是对象，就有相应的属性，且可以赋值：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 函数对象的属性</span></span><br><span class="line"><span class="built_in">print</span>(factorial.__doc__)</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(factorial))</span><br><span class="line"><span class="comment"># 既然是一个函数对象，那么就可以赋值</span></span><br><span class="line">fact = factorial</span><br><span class="line"><span class="built_in">print</span>(fact)</span><br><span class="line"><span class="built_in">print</span>(fact(<span class="number">5</span>))</span><br></pre></td></tr></table></figure>
<p>输出结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">    <span class="keyword">return</span> n!</span><br><span class="line">    </span><br><span class="line">&lt;<span class="class"><span class="keyword">class</span> &#x27;<span class="title">function</span>&#x27;&gt;</span></span><br><span class="line"><span class="class">&lt;<span class="title">function</span> <span class="title">factorial</span> <span class="title">at</span> 0<span class="title">x00000184B923F288</span>&gt;</span></span><br><span class="line"><span class="class">120</span></span><br></pre></td></tr></table></figure>
<p>为了更好的理解函数作为对象的特征，可以看看下面这个例子：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 嵌套函数返回函数对象</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">make_averager</span>():</span></span><br><span class="line">    nums = []</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">averager</span>(<span class="params">new_value</span>):</span></span><br><span class="line">        nums.append(new_value)</span><br><span class="line">        total = <span class="built_in">sum</span>(nums)</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> total / <span class="built_in">len</span>(nums)</span><br><span class="line">    <span class="keyword">return</span> averager</span><br></pre></td></tr></table></figure>
<p>外层函数返回的是函数的对象，这样一来经过下面的测试可以得到预期结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">avg = make_averager()</span><br><span class="line"><span class="built_in">print</span>(avg)</span><br><span class="line"><span class="built_in">print</span>(avg(<span class="number">3</span>))</span><br></pre></td></tr></table></figure>
<p>输出结果如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;function make_averager.&lt;<span class="built_in">locals</span>&gt;.averager at <span class="number">0x00000184B923FDC8</span>&gt;</span><br><span class="line"><span class="number">3.0</span></span><br></pre></td></tr></table></figure>
<h1>高阶函数</h1>
<p>**特点：**接受函数作为参数或者函数作为返回结果。eg:map/reduce，sorted。</p>
<p>map/reduce/filter就是典型的高阶函数：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">num_list = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>]</span><br><span class="line"><span class="comment"># map需要传入一个函数对象</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(<span class="built_in">map</span>(factorial, num_list)))</span><br></pre></td></tr></table></figure>
<p>输出：<code>[1, 2, 6, 24, 120, 5040, 362880]</code></p>
<p>reduce和map的区别是，map只允许传入的函数只能接受1个参数，而reduce可以接受两个参数，如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> reduce</span><br><span class="line"></span><br><span class="line">lyst = [<span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(<span class="built_in">map</span>(<span class="keyword">lambda</span> x: x**<span class="number">2</span>, lyst)))</span><br><span class="line"><span class="built_in">print</span>(reduce(<span class="keyword">lambda</span> x, y: x + y, lyst))</span><br></pre></td></tr></table></figure>
<p><strong>注意reduce返回的是一个值，而不是一个可迭代对象。</strong></p>
<p>对于常见的加减乘除，还可以使用这种方式来实现：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> partial</span><br><span class="line"><span class="keyword">from</span> operator <span class="keyword">import</span> add, mul</span><br><span class="line">op_mul = partial(mul, <span class="number">3</span>)</span><br><span class="line">op_mul(<span class="number">9</span>)</span><br></pre></td></tr></table></figure>
<p>这个op_mul就相当于一个乘法运算对象，而且其中有一个值固定为3，现在就传入另外一个值即可。从这里就可以看出来partial的作用：</p>
<p><strong>对于一个函数，如果有几个参数是确定的，但是还有一部分不确定，可以将确定的参数传入，然后借助partial函数，将这个传入了几个确定参数之后的函数作为一个新的函数，接下来只用将剩余的参数传入这个新的函数即可。</strong></p>
<p>字典实现列表推导式：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 字典的列表推导式</span></span><br><span class="line">usernames = [<span class="string">&#x27;sophia&#x27;</span>, <span class="string">&#x27;emma&#x27;</span>, <span class="string">&#x27;olivia&#x27;</span>, <span class="string">&#x27;ava&#x27;</span>]</span><br><span class="line">name_dict = &#123;name: <span class="built_in">len</span>(name) <span class="keyword">for</span> name <span class="keyword">in</span> usernames&#125;</span><br><span class="line"><span class="built_in">print</span>(name_dict)</span><br></pre></td></tr></table></figure>
<p>输出结果如下：</p>
<p><code>&#123;'sophia': 6, 'emma': 4, 'olivia': 6, 'ava': 3&#125;</code></p>
<p>嵌套高阶函数：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 嵌套高阶函数</span></span><br><span class="line"><span class="comment"># 首先将num_list中的偶数筛选掉</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(<span class="built_in">map</span>(factorial, <span class="built_in">filter</span>(<span class="keyword">lambda</span> n: n % <span class="number">2</span>, num_list))))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 使用列表推导式实现上述功能</span></span><br><span class="line">result = [factorial(num) <span class="keyword">for</span> num <span class="keyword">in</span> num_list <span class="keyword">if</span> num % <span class="number">2</span>]</span><br><span class="line"><span class="built_in">print</span>(result)</span><br></pre></td></tr></table></figure>
<p>输出：</p>
<p><code>[1, 6, 120, 5040, 362880]</code></p>
<p><code>[1, 6, 120, 5040, 362880]</code></p>
<h1>python单下划线和双下划的区别</h1>
<p>python下划线有5种：</p>
<table>
<thead>
<tr>
<th>模式</th>
<th>样例</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td>单前导下划线</td>
<td><code>_xxx</code></td>
<td>约定俗成，仅供类内使用，外部不调用，但是强制调用还是可以的</td>
</tr>
<tr>
<td>双前导下划线</td>
<td><code>__xxx</code></td>
<td>强制不可外部调用，如果是函数，那么函数所在的类的子类无法轻易重写该函数</td>
</tr>
<tr>
<td>单末尾下划线</td>
<td><code>xxx_</code></td>
<td>防止和python内置关键字冲突</td>
</tr>
<tr>
<td>双前导和末尾下划线</td>
<td><code>__xxx__</code></td>
<td>python语义的特殊方法，尽量避免自己使用</td>
</tr>
<tr>
<td>单下划线</td>
<td><code>_</code></td>
<td>较多的用法是，该变量在下面的作用域内不会使用到</td>
</tr>
</tbody>
</table>
<p>下面就这几种模式来举一下例子：</p>
<p><strong>单前导下划线：</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span>():</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self._name = <span class="string">&quot;julia&quot;</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">a = A()</span><br><span class="line"><span class="comment"># 约定俗成，仅供类内使用，外部不调用，但是强制调用还是可以的</span></span><br><span class="line"><span class="built_in">print</span>(a._name)</span><br></pre></td></tr></table></figure>
<p>输出：julia</p>
<p><strong>双前导下划线：</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span>():</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.__name = <span class="string">&quot;julia&quot;</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">a = A()</span><br><span class="line"><span class="comment"># 强制不可外部调用</span></span><br><span class="line"><span class="built_in">print</span>(a.__name)</span><br></pre></td></tr></table></figure>
<p>报错：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">---------------------------------------------------------------------------</span><br><span class="line">AttributeError                            Traceback (most recent call last)</span><br><span class="line">&lt;ipython-<span class="built_in">input</span>-<span class="number">24</span>-a75c7bdbf94f&gt; <span class="keyword">in</span> &lt;module&gt;</span><br><span class="line">      <span class="number">4</span>         <span class="keyword">pass</span></span><br><span class="line">      <span class="number">5</span> a = A()</span><br><span class="line">----&gt; <span class="number">6</span> <span class="built_in">print</span>(a.__name)</span><br><span class="line"></span><br><span class="line">AttributeError: <span class="string">&#x27;A&#x27;</span> <span class="built_in">object</span> has no attribute <span class="string">&#x27;__name&#x27;</span></span><br></pre></td></tr></table></figure>
<p>如果是带双前导下划线的函数：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span>():</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.__name = <span class="string">&quot;julia&quot;</span></span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__getname</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.__name</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span>(<span class="params">A</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__getname</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">dir</span>(A))</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">dir</span>(B))</span><br></pre></td></tr></table></figure>
<p>运行结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[<span class="string">&#x27;_A__getname&#x27;</span>, <span class="string">&#x27;__class__&#x27;</span>, <span class="string">&#x27;__delattr__&#x27;</span>, <span class="string">&#x27;__dict__&#x27;</span>, <span class="string">&#x27;__dir__&#x27;</span>, <span class="string">&#x27;__doc__&#x27;</span>, <span class="string">&#x27;__eq__&#x27;</span>, <span class="string">&#x27;__format__&#x27;</span>, <span class="string">&#x27;__ge__&#x27;</span>, <span class="string">&#x27;__getattribute__&#x27;</span>, <span class="string">&#x27;__gt__&#x27;</span>, <span class="string">&#x27;__hash__&#x27;</span>, <span class="string">&#x27;__init__&#x27;</span>, <span class="string">&#x27;__init_subclass__&#x27;</span>, <span class="string">&#x27;__le__&#x27;</span>, <span class="string">&#x27;__lt__&#x27;</span>, <span class="string">&#x27;__module__&#x27;</span>, <span class="string">&#x27;__ne__&#x27;</span>, <span class="string">&#x27;__new__&#x27;</span>, <span class="string">&#x27;__reduce__&#x27;</span>, <span class="string">&#x27;__reduce_ex__&#x27;</span>, <span class="string">&#x27;__repr__&#x27;</span>, <span class="string">&#x27;__setattr__&#x27;</span>, <span class="string">&#x27;__sizeof__&#x27;</span>, <span class="string">&#x27;__str__&#x27;</span>, <span class="string">&#x27;__subclasshook__&#x27;</span>, <span class="string">&#x27;__weakref__&#x27;</span>]</span><br><span class="line">[<span class="string">&#x27;_A__getname&#x27;</span>, <span class="string">&#x27;_B__getname&#x27;</span>, <span class="string">&#x27;__class__&#x27;</span>, <span class="string">&#x27;__delattr__&#x27;</span>, <span class="string">&#x27;__dict__&#x27;</span>, <span class="string">&#x27;__dir__&#x27;</span>, <span class="string">&#x27;__doc__&#x27;</span>, <span class="string">&#x27;__eq__&#x27;</span>, <span class="string">&#x27;__format__&#x27;</span>, <span class="string">&#x27;__ge__&#x27;</span>, <span class="string">&#x27;__getattribute__&#x27;</span>, <span class="string">&#x27;__gt__&#x27;</span>, <span class="string">&#x27;__hash__&#x27;</span>, <span class="string">&#x27;__init__&#x27;</span>, <span class="string">&#x27;__init_subclass__&#x27;</span>, <span class="string">&#x27;__le__&#x27;</span>, <span class="string">&#x27;__lt__&#x27;</span>, <span class="string">&#x27;__module__&#x27;</span>, <span class="string">&#x27;__ne__&#x27;</span>, <span class="string">&#x27;__new__&#x27;</span>, <span class="string">&#x27;__reduce__&#x27;</span>, <span class="string">&#x27;__reduce_ex__&#x27;</span>, <span class="string">&#x27;__repr__&#x27;</span>, <span class="string">&#x27;__setattr__&#x27;</span>, <span class="string">&#x27;__sizeof__&#x27;</span>, <span class="string">&#x27;__str__&#x27;</span>, <span class="string">&#x27;__subclasshook__&#x27;</span>, <span class="string">&#x27;__weakref__&#x27;</span>]</span><br></pre></td></tr></table></figure>
<p>这里的<code>__getname</code>函数是带前导双下划线的函数，第一个输出的时候，发现<code>__getname</code>的名称前面添加了<code>_A</code>，B类也有一个自己的函数<code>_B__getname</code>，在python中这种用法是为了避免和子类定义的函数名称冲突。</p>
<p><strong>单末尾下划线：</strong></p>
<p>这种用法是为了避免定义的变量和python的关键字冲突，比如<code>class</code>，这个时候可以使用<code>class_</code>来代替。</p>
<p><strong>单下划线：</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;000&quot;</span>)</span><br></pre></td></tr></table></figure>
<p>比如这种情况就没有使用到循环变量，可以使用_来代替。</p>
<p>参考：<a target="_blank" rel="noopener" href="https://blog.csdn.net/sinat_38682860/article/details/96902828">https://blog.csdn.net/sinat_38682860/article/details/96902828</a></p>
<h1>函数参数的特殊情况</h1>
<p>下面需要实现一个html标签，如<code>&lt;p&gt;hello&lt;/p&gt;</code>，<code>&lt;item class='' size='small'&gt;a&lt;/item&gt;</code>。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">make_element</span>(<span class="params">name, *contents, cls=<span class="literal">None</span>, **kwargs</span>):</span></span><br><span class="line">    <span class="keyword">if</span> cls:</span><br><span class="line">        kwargs[<span class="string">&#x27;class&#x27;</span>] = cls</span><br><span class="line">    </span><br><span class="line">    pairs = [<span class="string">f&quot;<span class="subst">&#123;attr&#125;</span>=<span class="subst">&#123;value&#125;</span>&quot;</span> <span class="keyword">for</span> attr, value <span class="keyword">in</span> kwargs.items()]</span><br><span class="line">    attr_str = <span class="string">&#x27; &#x27;</span>.join(pairs)</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> contents:</span><br><span class="line">        <span class="keyword">return</span> <span class="string">f&quot;&lt;<span class="subst">&#123;name&#125;</span> <span class="subst">&#123;attr_str&#125;</span>/&gt;&quot;</span></span><br><span class="line">    </span><br><span class="line">    elements = [<span class="string">f&quot;&lt;<span class="subst">&#123;name&#125;</span> <span class="subst">&#123;attr_str&#125;</span>&gt;<span class="subst">&#123;content&#125;</span>&lt;<span class="subst">&#123;name&#125;</span>/&gt;&quot;</span> <span class="keyword">for</span> content <span class="keyword">in</span> contents]</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;\n&#x27;</span>.join(elements)</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(make_element(<span class="string">&quot;p&quot;</span>, <span class="string">&quot;hello&quot;</span>, <span class="string">&quot;world&quot;</span>, cls=<span class="string">&quot;sidebar&quot;</span>, size=<span class="string">&quot;small&quot;</span>))</span><br></pre></td></tr></table></figure>
<p>输出：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;p size=small <span class="class"><span class="keyword">class</span>=<span class="title">sidebar</span>&gt;<span class="title">hello</span>&lt;<span class="title">p</span>/&gt;</span></span><br><span class="line"><span class="class">&lt;<span class="title">p</span> <span class="title">size</span>=<span class="title">small</span> <span class="title">class</span>=<span class="title">sidebar</span>&gt;<span class="title">world</span>&lt;<span class="title">p</span>/&gt;</span></span><br></pre></td></tr></table></figure>
<p>因为class是python中的关键字，传入函数的话会冲突，所以将cls特意拿出来接受class参数。现在想设计一个专门生成图片标签的函数，可以利用前面说到的partial函数，代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> partial</span><br><span class="line"></span><br><span class="line">image_make = partial(make_element, <span class="string">&quot;img&quot;</span>, cls=<span class="string">&quot;pic-frame&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(image_make(src=<span class="string">&quot;car.png&quot;</span>))</span><br><span class="line"></span><br><span class="line">item_make = partial(make_element, <span class="string">&quot;item&quot;</span>, size=<span class="string">&quot;small&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(item_make(<span class="string">&quot;A&quot;</span>, <span class="string">&quot;B&quot;</span>, <span class="string">&quot;C&quot;</span>))</span><br></pre></td></tr></table></figure>
<p>输出:</p>
<p><code>&lt;img src=car.png class=pic-frame/&gt; </code></p>
<p><code>&lt;item size=small&gt;A&lt;item/&gt; </code></p>
<p><code>&lt;item size=small&gt;B&lt;item/&gt; </code></p>
<p><code>&lt;item size=small&gt;C&lt;item/&gt;</code></p>
<p>这种涉及到的特殊参数是<code>*contents</code>和<code>**kwargs</code>，传入函数之后，contents是一个元组，kwargs是一个字典，如果需要对元组和字典进行解包，可以使用如下的方式：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># *解包元组</span></span><br><span class="line">a = (<span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line"><span class="built_in">print</span>(*a)</span><br><span class="line"><span class="comment"># **解包字典</span></span><br><span class="line">dict_a = &#123;<span class="string">&quot;a&quot;</span>: <span class="number">1</span>, <span class="string">&quot;b&quot;</span>: <span class="number">2</span>&#125;</span><br><span class="line">dict_b = &#123;<span class="string">&quot;c&quot;</span>: <span class="number">3</span>, <span class="string">&quot;d&quot;</span>: <span class="number">4</span>&#125;</span><br><span class="line">new_dict = &#123;**dict_a, **dict_b&#125;</span><br><span class="line"><span class="built_in">print</span>(new_dict)</span><br></pre></td></tr></table></figure>
<p>输出：</p>
<p><code>2 3 4 5 </code></p>
<p><code>&#123;'a': 1, 'b': 2, 'c': 3, 'd': 4&#125;</code></p>
<h1>装饰器</h1>
<p>装饰器的本质：在不改变函数签名、返回值的情况下，增加额外的功能。</p>
<h3 id="带运行时间的装饰器">带运行时间的装饰器</h3>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">build_func_with_time_record</span>(<span class="params">func</span>):</span></span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">wrapper</span>(<span class="params">*args, **kwargs</span>):</span></span><br><span class="line">        start = time.time()</span><br><span class="line">        result = func(*args, **kwargs)</span><br><span class="line">        end = time.time()</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">f&quot;function <span class="subst">&#123;func.__name__&#125;</span> cost <span class="subst">&#123;end - start&#125;</span>&quot;</span>)</span><br><span class="line">    <span class="keyword">return</span> wrapper</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">func_foo</span>(<span class="params">a, b</span>):</span></span><br><span class="line">    time.sleep(<span class="number">2</span>)</span><br><span class="line">    <span class="built_in">print</span>(a + b)</span><br><span class="line"></span><br><span class="line">new_func = build_func_with_time_record(func_foo)</span><br><span class="line">new_func(<span class="number">1</span>, <span class="number">3</span>)</span><br></pre></td></tr></table></figure>
<p>这段代码实现的就是在<code>func_foo</code>函数的基础上，再“装饰”一下，实现装饰功能的函数是<code>build_func_with_time_record</code>。</p>
<p>python提供了<code>@语法糖</code>来简化上述的“装饰”过程，使用<code>@</code>关键字可以将上述代码简化为：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">build_func_with_time_record</span>(<span class="params">func</span>):</span></span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">wrapper</span>(<span class="params">*args, **kwargs</span>):</span></span><br><span class="line">        start = time.time()</span><br><span class="line">        result = func(*args, **kwargs)</span><br><span class="line">        end = time.time()</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">f&quot;function <span class="subst">&#123;func.__name__&#125;</span> cost <span class="subst">&#123;end - start&#125;</span>&quot;</span>)</span><br><span class="line">        <span class="keyword">return</span> result</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> wrapper</span><br><span class="line"></span><br><span class="line"><span class="meta">@build_func_with_time_record</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">func_foo</span>(<span class="params">a, b</span>):</span></span><br><span class="line">    time.sleep(<span class="number">2</span>)</span><br><span class="line">    <span class="built_in">print</span>(a + b)</span><br><span class="line"></span><br><span class="line">func_foo(<span class="number">1</span>, <span class="number">3</span>)</span><br></pre></td></tr></table></figure>
<p>通过这种方式可以省去显示的将函数传入、赋值等操作。注意，上述的函数有参数a，b。参数不是通过<code>build_func_with_time_record</code>传入的，而是通过里面的<code>wrapper</code>函数传入的。</p>
<p>这样，可以将这个装饰器加在上述的<code>make_element</code>函数上：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@build_func_with_time_record</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">make_element</span>(<span class="params">name, *contents, cls=<span class="literal">None</span>, **kwargs</span>):</span></span><br><span class="line">    <span class="string">&quot;&quot;&quot;make HTML element</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    Args:</span></span><br><span class="line"><span class="string">        name (label name): such as p</span></span><br><span class="line"><span class="string">        cls (str, optional): make a distinction with class. Defaults to None.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    Returns:</span></span><br><span class="line"><span class="string">        str: the results</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">if</span> cls:</span><br><span class="line">        kwargs[<span class="string">&#x27;class&#x27;</span>] = cls</span><br><span class="line">    </span><br><span class="line">    pairs = [<span class="string">f&quot;<span class="subst">&#123;attr&#125;</span>=<span class="subst">&#123;value&#125;</span>&quot;</span> <span class="keyword">for</span> attr, value <span class="keyword">in</span> kwargs.items()]</span><br><span class="line">    attr_str = <span class="string">&#x27; &#x27;</span>.join(pairs)</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> contents:</span><br><span class="line">        <span class="keyword">return</span> <span class="string">f&quot;&lt;<span class="subst">&#123;name&#125;</span> <span class="subst">&#123;attr_str&#125;</span>/&gt;&quot;</span></span><br><span class="line">    </span><br><span class="line">    elements = [<span class="string">f&quot;&lt;<span class="subst">&#123;name&#125;</span> <span class="subst">&#123;attr_str&#125;</span>&gt;<span class="subst">&#123;content&#125;</span>&lt;<span class="subst">&#123;name&#125;</span>/&gt;&quot;</span> <span class="keyword">for</span> content <span class="keyword">in</span> contents]</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;\n&#x27;</span>.join(elements)</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(make_element(<span class="string">&quot;p&quot;</span>, <span class="string">&quot;hello&quot;</span>, <span class="string">&quot;world&quot;</span>, cls=<span class="string">&quot;sidebar&quot;</span>, size=<span class="string">&quot;small&quot;</span>))</span><br></pre></td></tr></table></figure>
<p>输出如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">function make_element cost <span class="number">0.0</span></span><br><span class="line">&lt;p size=small <span class="class"><span class="keyword">class</span>=<span class="title">sidebar</span>&gt;<span class="title">hello</span>&lt;<span class="title">p</span>/&gt;</span></span><br><span class="line"><span class="class">&lt;<span class="title">p</span> <span class="title">size</span>=<span class="title">small</span> <span class="title">class</span>=<span class="title">sidebar</span>&gt;<span class="title">world</span>&lt;<span class="title">p</span>/&gt;</span></span><br></pre></td></tr></table></figure>
<p>但是，此时我们再输出函数属性：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(make_element.__doc__)</span><br><span class="line"><span class="built_in">print</span>(make_element.__name__)</span><br><span class="line"><span class="comment"># 测试一下函数签名：</span></span><br><span class="line"><span class="keyword">from</span> inspect <span class="keyword">import</span> signature</span><br><span class="line">signature(make_element)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="literal">None</span></span><br><span class="line">wrapper</span><br><span class="line">&lt;Signature (*args, **kwargs)&gt;</span><br></pre></td></tr></table></figure>
<p>发现<strong>函数的属性</strong>和<strong>函数签名</strong>都发生了变化，我们回到不使用<code>@</code>关键字实现装饰器功能的代码上，发现<code>build_func_with_time_record</code>函数返回值就是wrapper函数对象，所以最后我们得到的不再是一开始的<code>make_element</code>函数了，那么有什么方法能解决这个问题呢？</p>
<p>需要将一开始的<code>build_func_with_time_record</code>做一下修改：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> wraps</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">build_func_with_time_record</span>(<span class="params">func</span>):</span></span><br><span class="line">    </span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    wraps在装饰器函数返回之前</span></span><br><span class="line"><span class="string">    通过获取func的属性</span></span><br><span class="line"><span class="string">    并存储在返回的最终函数中设置上述属性。</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line"><span class="meta">    @wraps(<span class="params">func</span>)</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">wrapper</span>(<span class="params">*args, **kwargs</span>):</span></span><br><span class="line">        start = time.time()</span><br><span class="line">        result = func(*args, **kwargs)</span><br><span class="line">        end = time.time()</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">f&quot;function <span class="subst">&#123;func.__name__&#125;</span> cost <span class="subst">&#123;end - start&#125;</span>&quot;</span>)</span><br><span class="line">        <span class="keyword">return</span> result</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> wrapper</span><br></pre></td></tr></table></figure>
<p>然后重新尝试一下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(make_element.__doc__)</span><br><span class="line"><span class="built_in">print</span>(make_element.__name__)</span><br><span class="line"><span class="comment"># 测试一下函数签名：</span></span><br><span class="line"><span class="keyword">from</span> inspect <span class="keyword">import</span> signature</span><br><span class="line">signature(make_element)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">make HTML element</span><br><span class="line"></span><br><span class="line">    Args:</span><br><span class="line">        name (label name): such <span class="keyword">as</span> p</span><br><span class="line">        cls (<span class="built_in">str</span>, optional): make a distinction <span class="keyword">with</span> <span class="keyword">class</span>. Defaults to <span class="literal">None</span>.</span><br><span class="line"></span><br><span class="line">    Returns:</span><br><span class="line">        <span class="built_in">str</span>: the results</span><br><span class="line">    </span><br><span class="line">make_element</span><br><span class="line">&lt;Signature (name, *contents, cls=<span class="literal">None</span>, **kwargs)&gt;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    
        <div class="reward-container">
  <div>行行好，赏一杯咖啡吧~</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.jpg" alt="WXL 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.jpg" alt="WXL 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>WXL
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://wangxl12.github.io/2021/10/23/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/python%E9%AB%98%E7%BA%A7%E7%BC%96%E7%A8%8B-part1/" title="python高级编程-part1">https://wangxl12.github.io/2021/10/23/编程语言/python高级编程-part1/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/python%E9%AB%98%E7%BA%A7%E7%BC%96%E7%A8%8B/" rel="tag"><i class="fa fa-tag"></i> python高级编程</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/10/12/Docker/Docker%E5%85%A5%E9%97%A8/" rel="prev" title="Docker入门">
      <i class="fa fa-chevron-left"></i> Docker入门
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/10/24/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/pytorch%E7%9A%84%E8%87%AA%E5%8A%A8%E6%B1%82%E5%AF%BC/" rel="next" title="pytorch的自动求导">
      pytorch的自动求导 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">1.</span> <span class="nav-text">outline</span></a></li><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">2.</span> <span class="nav-text">一等函数</span></a></li><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">3.</span> <span class="nav-text">高阶函数</span></a></li><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">4.</span> <span class="nav-text">python单下划线和双下划的区别</span></a></li><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">5.</span> <span class="nav-text">函数参数的特殊情况</span></a></li><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">6.</span> <span class="nav-text">装饰器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B8%A6%E8%BF%90%E8%A1%8C%E6%97%B6%E9%97%B4%E7%9A%84%E8%A3%85%E9%A5%B0%E5%99%A8"><span class="nav-number">6.0.1.</span> <span class="nav-text">带运行时间的装饰器</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="WXL"
      src="/images/td.jpg">
  <p class="site-author-name" itemprop="name">WXL</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">49</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">33</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/wangxl12" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wangxl12" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wxl.1.2.3@qq.com" title="E-Mail → mailto:wxl.1.2.3@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://blog.csdn.net/weixin_43141320?spm=1000.2115.3001.5343" title="https:&#x2F;&#x2F;blog.csdn.net&#x2F;weixin_43141320?spm&#x3D;1000.2115.3001.5343" rel="noopener" target="_blank">My CSDN Blog</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://blog.kilig.ink/" title="http:&#x2F;&#x2F;blog.kilig.ink&#x2F;" rel="noopener" target="_blank">HuangPiSong</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">WXL</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>


  <script defer src="/lib/three/three.min.js"></script>
    <script defer src="/lib/three/three-waves.min.js"></script>


  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













  

  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 's5o4gRGNyYbPVRfziI5EzhO1-gzGzoHsz',
      appKey     : 'N7aQtR2SU9AwgaO2YtVhRO0W',
      placeholder: "发表你的评论吧~",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : true,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
